package com.liwenfeng.diancanspringboot.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liwenfeng.diancanspringboot.common.constant.MessageConstant;
import com.liwenfeng.diancanspringboot.common.constant.PasswordConstant;
import com.liwenfeng.diancanspringboot.common.constant.StatusConstant;
import com.liwenfeng.diancanspringboot.common.context.BaseContext;
import com.liwenfeng.diancanspringboot.common.exception.AccountLockedException;
import com.liwenfeng.diancanspringboot.common.exception.AccountNotFoundException;
import com.liwenfeng.diancanspringboot.common.exception.PasswordEditFailedException;
import com.liwenfeng.diancanspringboot.common.exception.PasswordErrorException;
import com.liwenfeng.diancanspringboot.common.result.PageResult;
import com.liwenfeng.diancanspringboot.mapper.EmployeeMapper;
import com.liwenfeng.diancanspringboot.pojo.dto.EmployeeDTO;
import com.liwenfeng.diancanspringboot.pojo.dto.EmployeeLoginDTO;
import com.liwenfeng.diancanspringboot.pojo.dto.EmployeePageQueryDTO;
import com.liwenfeng.diancanspringboot.pojo.dto.PasswordEditDTO;
import com.liwenfeng.diancanspringboot.pojo.entity.Employee;
import com.liwenfeng.diancanspringboot.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        String openId = employeeLoginDTO.getOpenId();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (!Objects.equals(employee.getStatus(), StatusConstant.ENABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        if (openId != null && !Objects.equals(openId, "") && !Objects.equals(employee.getOpenId(), openId)) {
            employeeMapper.updateOpenId(employee.getId(), openId);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        // 默认状态为启用
        employee.setStatus(StatusConstant.ENABLE);
        // 设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employeeMapper.insert(employee);
    }

    // 修改密码
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        Employee byId = employeeMapper.getById(BaseContext.getCurrentId());
        if (!oldPassword.equals(byId.getPassword())) {
            throw new PasswordEditFailedException("原密码错误！");
        }

        Employee employee = new Employee();
        employee.setId(BaseContext.getCurrentId());
        employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employeeMapper.update(employee);
    }

    // 修改员工状态-启用/禁用
    @Override
    public void changeStatus(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.update(employee);
    }

    // 员工分页查询
    @Override
    public PageResult list(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.selectByPage(employeePageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    // 根据id查询员工
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("****");
        return employee;
    }

    // 修改员工信息
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.update(employee);
    }

    // 删除员工 逻辑删除
    @Override
    public void delete(Long id) {
        Employee byId = employeeMapper.getById(id);
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(StatusConstant.DELETE);
        employee.setUsername(byId.getUsername() + "-" + System.currentTimeMillis());
        employeeMapper.update(employee);
    }

}
